package log

import (
	"io"
	"time"
	"github.com/gin-gonic/gin"
	"os"
	"go-pipe/api/utilsfile/logging"
)

var DefaultWriter io.Writer = os.Stdout

func Logger() gin.HandlerFunc {
	return LoggerWithWriter(DefaultWriter)
}

func LoggerWithWriter(out io.Writer, notlogged ...string) gin.HandlerFunc {

	var skip map[string]struct{}

	if length := len(notlogged); length > 0 {
		skip = make(map[string]struct{}, length)

		for _, path := range notlogged {
			skip[path] = struct{}{}
		}
	}

	return func(c *gin.Context) {
		// Start timer
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery

		// Process request
		c.Next()

		// Log only when path is not being skipped
		if _, ok := skip[path]; !ok {
			// Stop timer
			end := time.Now()
			latency := end.Sub(start)

			clientIP := c.ClientIP()
			method := c.Request.Method
			statusCode := c.Writer.Status()
			//var statusColor, methodColor, resetColor string
			comment := c.Errors.ByType(gin.ErrorTypePrivate).String()

			if raw != "" {
				path = path + "?" + raw
			}

			//fmt.Fprintf(out, "[costom] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",
			//	end.Format("2006-01-02 15:04:05"),
			//	statusColor, statusCode, resetColor,
			//	latency,
			//	clientIP,
			//	methodColor, method, resetColor,
			//	path,
			//	comment,
			//)

			logging.Println(end.Format("2006-01-02 15:04:05"), latency.String(), clientIP, method, path, comment, statusCode)
		}
	}
}
